/*
 * File:   UserDelay.c
 * Author: Honrun
 */
#include "ch32x035.h"
#include "stdint.h"

#include "DevicesTime.h"
#include "DevicesDelay.h"

/*
 * Return:      void
 * Parameters:  void
 * Description: DWT初始化
 */
void vSysTickDelayInit(void)
{
    /* DISABLE */
    SysTick->CTLR = 0;
    /* Clear state */
    SysTick->SR = 0;
    /* Load the SysTick Counter Value */
    SysTick->CNT = 0;
    /* Set the SysTick Counter Load */
    SysTick->CMP = 0xFFFFFFFFFFFFFFFFULL;
    /* ENABLE */
    SysTick->CTLR = SysTick_CTLR_STE_Msk | SysTick_CTLR_STCLK_Msk;
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 秒延时
 */
void vSysTickDelayS(float fTime)
{
    vSysTickDelayUs(fTime * 1000000.0f);
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 毫秒延时
 */
void vSysTickDelayMs(float fTime)
{
    vSysTickDelayUs(fTime * 1000.0f);
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 微秒延时
 */
void vSysTickDelayUs(float fTime)
{
    uint64_t ulTimeStop = SysTick->CNT + (uint64_t)(fTime * (SystemCoreClock / 1000000));

    if(fTime < 0.0f)
        return;

    while(SysTick->CNT < ulTimeStop);
}

/*
 * Return:      void
 * Parameters:  void
 * Description: DWT初始化
 */
void vTimerDelayInit(void)
{
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 秒延时
 */
void vTimerDelayS(float fTime)
{
    vTimerDelayUs(fTime * 1000000.0f);
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 毫秒延时
 */
void vTimerDelayMs(float fTime)
{
    vTimerDelayUs(fTime * 1000.0f);
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 微秒延时
 */
void vTimerDelayUs(float fTime)
{
    uint64_t ulTimeStop = lTimebaseGet() + (uint64_t)fTime;

    while(lTimebaseGet() < ulTimeStop);
}
